<template>
  <div class="login_container">
    <router-link to="/home">home</router-link>
    <router-view />

    <div class="login_box">
      <!--登陆表单区域-->
      <el-form
        ref="loginFormRef"
        label-width="80px"
        class="login_form"
        :model="loginForm"
        :rules="loginFormRules"
      >
        <img src="../assets/img/logo.png" />

        <!--用户名-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <!--密码-->
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <!--按钮-->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登陆</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login } from ".././request/api";
import { post } from ".././request/";
export default {
  name: "Login",
  data() {
    return {
      // 登陆数据绑定
      loginForm: {
        username: "",
        password: ""
      },
      // 表达那验证规则对象
      loginFormRules: {
        // 验证用户名
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        // 验证密码
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return;
        console.log(this.loginForm);
        const res = await post(login, this.loginForm);
        console.log(res);
        if (res.code !== 0) return this.$message.error("登陆失败");
        this.$message.success("登陆成功");
        this.$store.commit("setToken", res.data.token);
        window.sessionStorage.setItem("token", res.data.token);
        this.$router.push("/home");
      });
    }
  },
  created() {
    const token = window.sessionStorage.getItem("token");
    if (token) {
      this.$router.push("/home");
    }
  }
};
</script>

<style  scoped>
img {
  position: absolute;
  left: 45%;
  top: -35%;
}
.login_container {
  height: 100%;
  background-image: url("../assets/img/BGI.png");
  border-radius: 10px;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.login_form {
  position: relative;
  top: 25%;
}
.el-input {
  position: relative;
  font-size: 14px;
  display: inline-block;
  width: 80%;
}
.el-button {
  position: relative;
  left: 10%;
  width: 60%;
}
</style>
